;
(function(_$) {

    const question = {
        init: function(selector, parentForm, dt) {
            const qus = {
                _selectorContainer: selector,
                _selectorContent: undefined,
                _selectorTextAnalysis: undefined,
                _ueContent: null,
                _ueTextAnalysis: null,
                _questionForm: undefined,
                _childQuestion: [],
                _selectorOption: undefined,
                _parentForm: parentForm,
                destroy: function() {
                    this._ueContent.destroy();
                    this._ueTextAnalysis.destroy();
                    this._ueContent = this._ueTextAnalysis = null;
                    _$(`#${this._selectorContent}`).remove();
                    _$(`#${this._selectorTextAnalysis}`).remove();
                    
                    _$(this._selectorContainer).empty();
                },
                getQuestion: function() {
                    return {
                        content: this._ueContent.getContent(),
                        text_analysis: this._ueTextAnalysis.getContent(),
                        remark: _$(`${this._selectorContainer} #remark`).val(),
                        children: this._childQuestion,
                    };
                },
                reset: function() {
                    _$(`${this._selectorContainer} .${this._selectorOption} tbody`).empty();
                    _$(`${this._selectorContainer} #remark`).val("");
                    this._ueContent.setContent("");
                    this._ueTextAnalysis.setContent("");
                },
            };
            _$(qus._selectorContainer).empty().append(getHtml(qus));
            bindListener(qus);
            initUE(qus);
            initData(qus, dt);
            return qus;
        },
    };
    
    function getHtml(qus) {
        const d = new Date();
        qus._selectorContent = `question-content-${d.getTime()}`;
        qus._selectorTextAnalysis = `question-text-analysis-${d.getTime()}`;
        qus._selectorOption = `option-list-${d.getTime()}`;
        
        const htmlStr = `<div class="form-group">
            <label for="analysis" class="col-sm-2 control-label">题干</label>
            <div class="col-sm-10">
                <script type="text/plain" id="${qus._selectorContent}"></script>
            </div>
        </div>
        <div class="form-group">
            <label for="analysis" class="col-sm-2 control-label">小题</label>
            <div class="col-sm-10">
                <button type="button" class="btn btn-primary btn-sm btn-add-answer">添加</button>
                <button type="button" class="btn btn-danger btn-sm btn-remove-answer">删除</button>
                <table class="table ${qus._selectorOption}">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>试题</th>
                            <th style="width: 150px;">操作</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>
        <div class="form-group">
            <label for="analysis" class="col-sm-2 control-label">解析</label>
            <div class="col-sm-10">
                <script type="text/plain" id="${qus._selectorTextAnalysis}"></script>
            </div>
        </div>
        <div class="form-group">
            <label for="remark" class="col-sm-2 control-label">备注</label>
            <div class="col-sm-10">
                <textarea class="form-control" name="remark" id="remark"></textarea>
            </div>
        </div>`;
        return htmlStr;
    }
    
    function bindListener(qus) {
        _$(`${qus._selectorContainer} .btn-add-answer`).click(function () {
            const dialogQuestionContainer = `dialog-question-container-${Date.now()}`;
            const d = dialog({
                title: "添加试题",
                content: `<div class="${dialogQuestionContainer}" style="overflow: auto;height: 100%;"></div>`,
                height: "80vh",
                width: "90vw",
                ok: function () {
                    const val = qus._questionForm.getQuestion();
                    if (!val) {
                        return false;
                    }
                    qus._childQuestion.push(val);
                    if (!val.base.id && !val.base.tid) {
                        val.base.tid = Date.now();
                    }
                    console.warn(val);
                    console.warn(`<p>[题干]${val.content.content}</p>`);
                    console.warn(val.content.answer);
                    const sid = val.base.id || val.base.tid;
                    _$(`${qus._selectorContainer} .${qus._selectorOption} tbody`).append(`
                        <tr id="${sid}">
                            <td><input type="checkbox" name="read-analysis-cb" value="${sid}"></td>
                            <td>
                                <div>[题干]${val.content.content.slice(3).slice(0, -4)}</div>
                                <p>[参考答案]${val.content.answer}</p>
                            </td>
                            <td style="width: 150px;">
                                <button type="button" class="btn btn-primary btn-sm" id="${sid}-edit">编辑</button>
                                <button type="button" class="btn btn-primary btn-sm" id="${sid}-detail">详情</button>
                                <button type="button" class="btn btn-danger btn-sm" id="${sid}-del">删除</button>
                            </td>
                    </tr>`);
                    bindChildListener(qus, sid);
                },
                okValue: "确定",
                cancelValue: '取消',
	            cancel: function () {},
                onshow: function () {
                    console.warn("onshow");
                    qus._questionForm = _$.fn.questionForm.init(`.${dialogQuestionContainer}`, {
                        questionTypeAllow: ["single", "fill", "multiple"],
                    }, {
                        base: qus._parentForm.getQuestionBase(),
                    });
                },
                onremove: function () {
                    console.warn("onremove");
                    qus._questionForm && qus._questionForm.destroy();
                    qus._questionForm = null;
                },
            });
            d.show();
        });
    
        _$(`${qus._selectorContainer} .btn-remove-answer`).click(function () {
            _$(`${qus._selectorContainer} input[name="read-analysis-cb"]:checked`).each(function () {
                const tid = _$(this).val();
                _$(`${qus._selectorContainer} #${tid}`).remove();
                const idx  = qus._childQuestion.findIndex((item) => item.bsae.id == tid || item.base.tid == tid);
                if (idx >= 0) {
                    qus._childQuestion.splice(idx, 1);
                }
            });
        });
    }
    
    function bindChildListener(qus, sid) {
        _$(`${qus._selectorContainer} #${sid}-edit`).click(function () {
            const item  = qus._childQuestion.find((item) => item.base.id == sid || item.base.tid == sid);
            console.warn(qus, sid, item);
            if (!item) {
                return;
            }
            const dialogQuestionContainer = `dialog-question-container-${Date.now()}`;
            const d = dialog({
                title: "编辑试题",
                content: `<div class="${dialogQuestionContainer}" style="overflow: auto;height: 100%;"></div>`,
                height: "80vh",
                width: "90vw",
                ok: function () {
                    const val = qus._questionForm.getQuestion();
                    console.warn(val);
                    if (!val) {
                        return false;
                    }
                    const ssid = val.base.id || val.base.tid;
                    console.warn('ssid', ssid);
                    const idx = qus._childQuestion.findIndex((item) => {
                        console.warn('item', item.base.id, item.base.tid);
                        return item.base.id == ssid || ssid == item.base.tid;
                    });
                    console.warn(qus._childQuestion);
                    if (idx < 0) {
                        return false;
                    }
                    console.warn('idx', idx);
                    const delVal = qus._childQuestion.splice(idx, 1, val);
                    console.warn('delVal', delVal);
                    _$(`${qus._selectorContainer} #${ssid} td:nth-child(2)`).empty().append(`
                        <div>[题干]${val.content.content.slice(3).slice(0, -4)}</div>
                        <p>[参考答案]${val.content.answer}</p>`);
                },
                okValue: "确定",
                cancelValue: "取消",
	            cancel: function () {

                },
                onshow: function () {
                    console.warn("onshow");
                    qus._questionForm = _$.fn.questionForm.init(`.${dialogQuestionContainer}`, {}, item);
                },
                onremove: function () {
                    console.warn("onremove");
                    qus._questionForm && qus._questionForm.destroy();
                    qus._questionForm = null;
                },
            });
            d.show();
        });

        console.warn(`${qus._selectorContainer} #${sid}-detail`);
        _$(`${qus._selectorContainer} #${sid}-detail`).click(function () {
            console.warn(sid, qus._childQuestion);
            const item  = qus._childQuestion.find((item) => item.base.id == sid || item.base.tid == sid);
            console.warn(item);
            if (!item) {
                return;
            }
            const dialogQuestionContainer = `dialog-question-container-${Date.now()}`;
            const d = dialog({
                title: "试题详情",
                content: `<div class="${dialogQuestionContainer}" style="overflow: auto;height: 100%;"></div>`,
                height: "80vh",
                width: "90vw",
                onshow: function () {
                    qus._questionForm = _$.fn.questionForm.init(`.${dialogQuestionContainer}`, {}, item);
                },
                onremove: function () {
                    qus._questionForm && qus._questionForm.destroy();
                    qus._questionForm = null;
                },
            });
            d.show();            
        });

        _$(`${qus._selectorContainer} #${sid}-del`).click(function () {
            _$(`${qus._selectorContainer} #${sid}`).remove();
            const idx  = qus._childQuestion.findIndex((item) => item.id == sid || item.tid == sid);
            if (idx >= 0) {
                qus._childQuestion.splice(idx, 1);
            }
        });
    }

    function initUE(qus) {
        console.warn(qus._selectorContent);
        console.warn(qus._selectorTextAnalysis);
        qus._ueContent = window.UE.getEditor(qus._selectorContent, {
            autoHeight: false
        });
        qus._ueTextAnalysis = window.UE.getEditor(qus._selectorTextAnalysis, {
            autoHeight: false
        });
        console.warn(qus._ueContent);
    }

    function initData(qus, dt) {
        console.warn(qus, dt);
        if (!dt) {
            return;
        }
        qus._ueContent.ready(function() {
            qus._ueContent.setContent(dt.content.content);
        });  
        qus._ueTextAnalysis.ready(function() {
            qus._ueTextAnalysis.setContent(dt.content.text_analysis);
        });
        _$(`${qus._selectorContainer} #remark`).val(dt.content.remark);
        dt.children.forEach((item) => {
            const sid = item.base.id;
            _$(`${qus._selectorContainer} .${qus._selectorOption} tbody`).append(`
                <tr id="${sid}">
                    <td><input type="checkbox" name="read-analysis-cb" value="${sid}"></td>
                    <td>
                        <div>[题干]${item.content.content}</div>
                        <p>[参考答案]${item.content.answer}</p>
                    </td>
                    <td style="width: 150px;">
                        <button type="button" class="btn btn-primary btn-sm" id="${sid}-edit">编辑</button>
                        <button type="button" class="btn btn-primary btn-sm" id="${sid}-detail">详情</button>
                        <button type="button" class="btn btn-danger btn-sm" id="${sid}-del">删除</button>
                    </td>
            </tr>`);
            bindChildListener(qus, sid);            
        });
        qus._childQuestion.push(...dt.children);
    }

    _$.fn.extend({
        questionReadAnalysis: question,
    });
})($);